//
//  TLLottieView.swift
//  Huaya
//
//  Created by huaya on 2025/3/28.
//  Copyright © 2025 HY. All rights reserved.
//


import UIKit
import Foundation
import Lottie

@objc
public enum FELottieBackgroundBehavior:Int {
    case fe_default = 0
    case fe_stop = 1
    case fe_pause = 2
    case fe_pauseAndRestore = 3
    case fe_forceFinish = 4
    case fe_continuePlaying = 5
}

@objc
open class TLLottieView: UIView {
    //动画
    @objc public var mAnimationView = LottieAnimationView()
    
    ///次数
    @objc public var loopAnimationCount: CGFloat = 0 {
        didSet {
            mAnimationView.loopMode = loopAnimationCount == -1 ? .loop : .repeat(Float(loopAnimationCount))
        }
    }
    
    /// 速度
    @objc public var speed: CGFloat = 1 {
        didSet {
            mAnimationView.animationSpeed = speed
        }
    }
    
    /// 程序到后台动画的行为
    @objc public var backgroundBehavior: FELottieBackgroundBehavior = .fe_default {
        didSet {
            switch backgroundBehavior {
            case .fe_stop:
                mAnimationView.backgroundBehavior = .stop
            case.fe_pause:
                mAnimationView.backgroundBehavior = .pause
            case.fe_pauseAndRestore:
                mAnimationView.backgroundBehavior = .pauseAndRestore
            case.fe_continuePlaying:
                mAnimationView.backgroundBehavior = .continuePlaying
            case .fe_forceFinish:
                mAnimationView.backgroundBehavior = .forceFinish
            case .fe_default:
                break
            }
        }
    }
    
    public init() {
        self.speed = 1
        self.loopAnimationCount = 0
        self.backgroundBehavior = .fe_default
        super.init(frame: .zero)
    }
    
    ///名称--创建动画
    @objc public convenience init(name: String) {
        self.init()
        
        // 优先从主 Bundle 查找
        if let jsonPath = Bundle.main.path(forResource: name, ofType: "json"),
           let animation = LottieAnimation.filepath(jsonPath) {
            setupAnimationView(animation: animation)
            return
        }
        
        // 若在主 Bundle 未找到，尝试从框架 Bundle 查找（适用于模块化场景）
        let frameworkBundle = Bundle(for: TLLottieView.self)
        if let jsonPath = frameworkBundle.path(forResource: name, ofType: "json"),
           let animation = LottieAnimation.filepath(jsonPath) {
            setupAnimationView(animation: animation)
            return
        }
        
        // 文件未找到处理
        assertionFailure("Lottie JSON 文件未找到: \(name).json")
    }
    
    private func setupAnimationView(animation: LottieAnimation) {
        mAnimationView.animation = animation
        self.addSubview(mAnimationView)
        mAnimationView.mas_makeConstraints { make in
            make?.left.mas_equalTo()(0)
            make?.right.mas_equalTo()(0)
            make?.top.mas_equalTo()(0)
            make?.bottom.mas_equalTo()(0)
        }
        mAnimationView.play()
    }
    
    ///远层--创建动画
    @objc public convenience init(remoteUrl:String) {
        self.init()
        weak var weakSelf = self
        if let url = URL(string: remoteUrl) {
            mAnimationView = LottieAnimationView(url:url, closure: { (error) in
                if let _ = error {
                    DispatchQueue.main.async {
                        weakSelf?.remove()
                    }
                } else {
                    DispatchQueue.main.async {
                        weakSelf?.showRemoteLottieWhenSuccess()
                    }
                }
            })
        }
    }
    
    ///远层动画成功
    fileprivate func showRemoteLottieWhenSuccess() {
        mAnimationView.contentMode = .scaleAspectFit
        self.addSubview(mAnimationView)
        mAnimationView.mas_makeConstraints { make in
            make?.left.mas_equalTo()(0)
            make?.right.mas_equalTo()(0)
            make?.top.mas_equalTo()(0)
            make?.bottom.mas_equalTo()(0)
        }
        mAnimationView.play()
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    ///播放动画
    @objc open func play(completion:@escaping() -> ()) {
        mAnimationView.play { (isu) in
            if Thread.isMainThread {
                completion()
            } else {
                DispatchQueue.main.async {
                    completion()
                }
            }
        }
    }
    
    ///播放动画
    @objc public func play() -> Void {
        mAnimationView.play()
    }
    
    ///暂停动画
    @objc public func pause() -> Void {
        mAnimationView.pause();
    }
    
    ///停止动画
    @objc public func stop() -> Void {
        mAnimationView.stop();
    }
    
    ///删除动画
    @objc public func remove() -> Void {
        mAnimationView.removeFromSuperview()
        self.removeFromSuperview()
    }
}

